/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 * 
 * CompanyServiceImpl.java
 */
package com.yixun.qfbao.service.impl;

import com.yixun.common.page.Page;
import com.yixun.qfbao.dao.DepartmentDao;
import com.yixun.qfbao.enums.QfSmsTemplateEnum;
import com.yixun.qfbao.mapper.CommissionRuleParentMapper;
import com.yixun.qfbao.mapper.CompanyMapper;
import com.yixun.qfbao.mapper.CompanyRelationMapper;
import com.yixun.qfbao.mapper.DepartmentMapper;
import com.yixun.qfbao.model.*;
import com.yixun.qfbao.model.dto.*;
import com.yixun.qfbao.model.enums.*;
import com.yixun.qfbao.service.*;
import com.yixun.qfbao.util.ChineseCharToEn;
import com.yixun.qfbao.util.PasswordUtil;
import com.yixun.qfbao.util.SMSUtil;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Pattern;


/**
 * [文件名称]<br>
 * CompanyServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 * 商户 service interface impl<br>
 * <br>
 * [修改记录]<br>
 * 2015-12-10 14:36:24 创建 陶俊代码生成器<br>
 *
 * @author 陶俊代码生成器
 * @version 1.00
 */
@Service("companyService")
public class CompanyServiceImpl implements CompanyService {
	private Logger logger = LoggerFactory.getLogger(CompanyServiceImpl.class);
	@Resource
	private CompanyMapper mapper;
	@Autowired
	private CompanyRelationMapper companyRelationMapper;
	@Autowired
	private DepartmentMapper departmentMapper;
	@Autowired
	private DepartmentDao departmentDao;
	@Autowired
	private CompanyRelationService companyRelationService;
	@Autowired
	private LogoService logoService;
	@Autowired
	private PartnerInfoService partnerInfoService;
	@Autowired
	private PremisesService premisesService;
	@Autowired
	private PremisesRelationService premisesRelationService;
	@Autowired
	private CommissionRuleParentMapper commissionRuleParentMapper;
	@Autowired
	private SmsSettingService smsSettingService;
	@Autowired
	private SmsHistoryService smsHistoryService;
	@Autowired
	private SMSUtil smsUtil;
	/**
	 * @param entity 搜索条件
	 * @param begin 分页开始行数[不包含]
	 * @param end 分页结束行数[包含]
	 * @return 分页记录
	 */
	@Transactional(readOnly = true)
	@Override
	public Page<Company> getPageModel(CompanyDto entity,int begin,int end){
		if(!entity.getStatusNotFilterFlag()) {
			if(StringUtils.isEmpty(entity.getStatus())) {
				entity.setStatus(CheckStatusEnum.SUCCESS.getNo());
			}
		}
		Integer total = mapper.count(entity);
		List<Company> rows = mapper.list(entity,begin,end);
	    Page<Company> msr = new Page<Company>(total, rows);
	    msr.setTotalPages((total %end == 0)? (total /end): (total /end + 1));
		return msr;
	}

	/**
	 * 查询列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	@Override
	public List<Company> selectListByDto(CompanyDto entity){
		return mapper.selectListByDto(entity);
	}
	/**
	 * 查询列表
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	@Override
	public List<Company> selectListInfo(CompanyDto entity){
		return mapper.selectListInfo(entity);
	}

	/**
	 * 查询单个
	 * @param entity 搜索条件
	 * @return 分页记录
	 */
	@Override
	public Company selectByDto(CompanyDto entity){
		return mapper.selectByDto(entity);
	}

	/**
	 * @param id 搜索条件
	 * @return 分页记录
	 */
	@Override
	public Company selectById(Long id){
		if(id!=null){
			return mapper.selectById(id);
		}
		return null;
	}
	/**
	 * @param id 搜索条件
	 * @return 分页记录
	 */
	@Override
	public CompanyDto selectByMyId(Long id){
		if(id!=null){
			return mapper.selectByMyId(id);
		}
		return null;
	}
	/**
	 * @param entity 新增记录的详细信息
	 * @return 新增行数
	 */
	@Override
	public CompanyDto create(CompanyDto entity) {
		entity.setCreateTime(Calendar.getInstance().getTime());
		//entity.setDelFlag(DelFlagEnum.UNDEL.getNo());//由于注册时当没有审核通过时默认时删除的，所以注释掉这里的代码
		entity.setCompanyUuid(UUID.randomUUID().toString());
		mapper.add(entity);
		//放在部门表中记录了，这里就注释了
		/*//记录用户操作日志
		OperationLogDto dto = new OperationLogDto();
		dto.setOptType(OptTypeEnum.ADD.getNo());
		dto.setOptTargetId(entity.getId());
		dto.setOptTime(Calendar.getInstance().getTime());
		dto.setOptUser(entity.getOptUser());
		dto.setOptTarget(OptTargetEnum.TYPE_1.getNo());
		operationLogMapper.add(dto);*/
		return entity;
	}

	/**
	 * @param entity 更新记录的详细信息
	 * @return 更新行数
	 */
	@Override
	public int update(CompanyDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		/*//记录用户操作日志
		OperationLogDto dto = new OperationLogDto();
		dto.setOptType(OptTypeEnum.EDIT.getNo());
		dto.setOptTargetId(entity.getId());
		dto.setOptTime(Calendar.getInstance().getTime());
		dto.setOptUser(entity.getOptUser());
		dto.setOptTarget(OptTargetEnum.TYPE_1.getNo());
		operationLogMapper.add(dto);*/
		return mapper.edit(entity);
	}
	
	/**
	 * @param entity 更新记录的详细信息
	 * @return 更新行数
	 */
	@Override
	public int updateByComapnyUuid(CompanyDto entity) {
		entity.setUpdateTime(new Date());
		return mapper.editByCompanyUuid(entity);
	}
	/**
	 * @param entity 更新记录的详细信息
	 * @return 更新行数
	 */
	@Override
	public int updateByMyid(CompanyDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		/*//记录用户操作日志
		OperationLogDto dto = new OperationLogDto();
		dto.setOptType(OptTypeEnum.EDIT.getNo());
		dto.setOptTargetId(entity.getId());
		dto.setOptTime(Calendar.getInstance().getTime());
		dto.setOptUser(entity.getOptUser());
		dto.setOptTarget(OptTargetEnum.TYPE_1.getNo());
		operationLogMapper.add(dto);*/
		return mapper.updateByMyid(entity);
	}

	/**
	 * @param entity 待删除的记录信息
	 * @return 删除行数
	 */
	@Override
	public int destroy(CompanyDto entity) {
		/*//记录用户操作日志
		OperationLogDto dto = new OperationLogDto();
		dto.setOptType(OptTypeEnum.DEL.getNo());
		dto.setOptTargetId(entity.getId());
		dto.setOptTime(Calendar.getInstance().getTime());
		dto.setOptUser(entity.getOptUser());
		dto.setOptTarget(OptTargetEnum.TYPE_1.getNo());
		operationLogMapper.add(dto);*/
		return mapper.del(entity);
	}

	/**
	 * @param entity 新增或更新
	 * @return 新增行数
	 */
	@Override
	public int saveOrUpdate(CompanyDto entity) {
		if(entity!=null&&entity.getId()!=null){
			updateLogo(entity);
			updateCompany(entity);
			return update(entity);
		}else{
			entity = create(entity);
			if(entity.getId()!=null){
				saveLogo(entity);
			}
			DepartmentDto departmentDto = new DepartmentDto();
			departmentDto.setDepartmentCode(String.valueOf(entity.getId()));
			if(entity.getParentId()==null){
				departmentDto.setParentId(0L);
			}else{
				departmentDto.setParentId(entity.getParentId());
			}
			departmentDto.setDepartmentName(entity.getCompanyName());
			departmentDto.setMerchantId(entity.getId());
			departmentDto.setCreateUserId(0L);
			departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			departmentDto.setUpdateTime(Calendar.getInstance().getTime());
			/*departmentDto.setReward(entity.getReward());
			departmentDto.setPremisesCommission(entity.getPremisesCommission());
			departmentDto.setCommission(entity.getCommission());
			departmentDto.setCommissionWay(entity.getCommissionWay());*/
			departmentDto.setPrincipal(entity.getPrincipal());
			departmentDto.setOptUser(entity.getOptUser());
			departmentDao.create(departmentDto);
			return 1;
		}
	}

	/**
	 * @param entity 根据pojo搜索如果主键为空则返回它本身
	 * @return 一行记录或本身
	 */
	@Override
	public Company selectBy(Company entity) {
		if(entity!=null&&entity.getId()!=null){
			return mapper.selectById(entity.getId());
		}
		return entity;
	}
	@Override
	public Page<Company> getDistributionPage(CompanyDto entity,int begin,int end){
		Integer total = mapper.count(entity);
		List<Company> rows = mapper.distributionReportlist(entity,begin,end);
	    Page<Company> msr = new Page<Company>(total, rows);
	    msr.setPageSize(end);
		return msr;
	}

	@Override
	public List<Company> agentCompanyMap(CompanyDto entity) {

		return mapper.agentCompanyMap(entity);
	}

	@Override
	public String isDevBindM2(String companyId, String companyType) {
		String merchantCode = "";
		if(CompanyTypeEnum.COMPANY_TYPE_VALUE_0.getCode().equals(companyType)){
			//中介公司
			CompanyRelationDto crDto = new CompanyRelationDto();
			crDto.setAgentCompany(Long.valueOf(companyId));
			crDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			CompanyRelation cr = companyRelationService.selectByDto(crDto);
			if(cr == null) {
			    return null;
            }
            Company company = mapper.selectById(cr.getDevCompany());
			if(company == null || !"1".equals(company.getLinkM2())) {
			    return null;
            }
            merchantCode = company.getMerchantCode();
		}else if(CompanyTypeEnum.COMPANY_TYPE_VALUE_2.getCode().equals(companyType)){
			//开发商
			Company company = mapper.selectById(Long.valueOf(companyId));
            if(company == null || !"1".equals(company.getLinkM2())) {
                return null;
            }
			merchantCode = company.getMerchantCode();
		}
		return merchantCode;
	}

	public void saveLogo(CompanyDto entity){
		if(StringUtils.isNotBlank(entity.getH5LoginLogo())){
			LogoDto logo1 = new LogoDto();
			logo1.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo1.setLogoMerchantid(entity.getId());
			logo1.setLogoType(LogoTypeEnum.TYPE_1.getNo());
			logo1.setLogoUrl(entity.getH5LoginLogo());
			logoService.create(logo1);
		}
		if(StringUtils.isNotBlank(entity.getAssiantLoginLogo())){
			LogoDto logo2 = new LogoDto();
			logo2.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo2.setLogoMerchantid(entity.getId());
			logo2.setLogoType(LogoTypeEnum.TYPE_2.getNo());
			logo2.setLogoUrl(entity.getAssiantLoginLogo());
			logoService.create(logo2);
		}
		if(StringUtils.isNotBlank(entity.getAssiantIndexLogo())){
			LogoDto logo3 = new LogoDto();
			logo3.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo3.setLogoMerchantid(entity.getId());
			logo3.setLogoType(LogoTypeEnum.TYPE_3.getNo());
			logo3.setLogoUrl(entity.getAssiantIndexLogo());
			logoService.create(logo3);
		}
		if(StringUtils.isNotBlank(entity.getAssiantExitLogo())){
			LogoDto logo4 = new LogoDto();
			logo4.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo4.setLogoMerchantid(entity.getId());
			logo4.setLogoType(LogoTypeEnum.TYPE_4.getNo());
			logo4.setLogoUrl(entity.getAssiantExitLogo());
			logoService.create(logo4);
		}
		if(StringUtils.isNotBlank(entity.getDevelopersLoginLogo())){
			LogoDto logo5 = new LogoDto();
			logo5.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo5.setLogoMerchantid(entity.getId());
			logo5.setLogoType(LogoTypeEnum.TYPE_5.getNo());
			logo5.setLogoUrl(entity.getDevelopersLoginLogo());
			logoService.create(logo5);
		}
		if(StringUtils.isNotBlank(entity.getDevelopersIndexLogo())){
			LogoDto logo6 = new LogoDto();
			logo6.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo6.setLogoMerchantid(entity.getId());
			logo6.setLogoType(LogoTypeEnum.TYPE_6.getNo());
			logo6.setLogoUrl(entity.getDevelopersIndexLogo());
			logoService.create(logo6);
		}
		if(StringUtils.isNotBlank(entity.getAgencyLoginLogo())){
			LogoDto logo7 = new LogoDto();
			logo7.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo7.setLogoMerchantid(entity.getId());
			logo7.setLogoType(LogoTypeEnum.TYPE_7.getNo());
			logo7.setLogoUrl(entity.getAgencyLoginLogo());
			logoService.create(logo7);
		}
		if(StringUtils.isNotBlank(entity.getAgencyIndexLogo())){
			LogoDto logo8 = new LogoDto();
			logo8.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo8.setLogoMerchantid(entity.getId());
			logo8.setLogoType(LogoTypeEnum.TYPE_8.getNo());
			logo8.setLogoUrl(entity.getAgencyIndexLogo());
			logoService.create(logo8);
		}
	}
	public void updateLogo(CompanyDto entity){
		if(StringUtils.isNotBlank(entity.getH5LoginLogo())){
			LogoDto logo1 = new LogoDto();
			logo1.setLogoMerchantid(entity.getId());
			logo1.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo1.setLogoType(LogoTypeEnum.TYPE_1.getNo());
			List<Logo> list = logoService.selectListByDto(logo1);
			if(list.size()==1){
				logo1.setLogoUrl(entity.getH5LoginLogo());
				logo1.setId(list.get(0).getId());
				logoService.update(logo1);
			}else if(list.size()==0){
				//当没找到对应logo,说明之前没上传过
				LogoDto saveEntity = new LogoDto();
				saveEntity.setDelFlag(DelFlagEnum.UNDEL.getNo());
				saveEntity.setLogoMerchantid(entity.getId());
				saveEntity.setLogoType(LogoTypeEnum.TYPE_1.getNo());
				saveEntity.setLogoUrl(entity.getH5LoginLogo());
				logoService.create(saveEntity);
			}
		}
		if(StringUtils.isNotBlank(entity.getAssiantLoginLogo())){
			LogoDto logo2 = new LogoDto();
			logo2.setLogoMerchantid(entity.getId());
			logo2.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo2.setLogoType(LogoTypeEnum.TYPE_2.getNo());
			List<Logo> list = logoService.selectListByDto(logo2);
			if(list.size()==1){
				logo2.setLogoUrl(entity.getAssiantLoginLogo());
				logo2.setId(list.get(0).getId());
				logoService.update(logo2);
			}else if(list.size()==0){
				//当没找到对应logo,说明之前没上传过
				LogoDto saveEntity = new LogoDto();
				saveEntity.setDelFlag(DelFlagEnum.UNDEL.getNo());
				saveEntity.setLogoMerchantid(entity.getId());
				saveEntity.setLogoType(LogoTypeEnum.TYPE_2.getNo());
				saveEntity.setLogoUrl(entity.getAssiantLoginLogo());
				logoService.create(saveEntity);
			}
		}
		if(StringUtils.isNotBlank(entity.getAssiantIndexLogo())){
			LogoDto logo3 = new LogoDto();
			logo3.setLogoMerchantid(entity.getId());
			logo3.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo3.setLogoType(LogoTypeEnum.TYPE_3.getNo());
			List<Logo> list = logoService.selectListByDto(logo3);
			if(list.size()==1){
				logo3.setLogoUrl(entity.getAssiantIndexLogo());
				logo3.setId(list.get(0).getId());
				logoService.update(logo3);
			}else if(list.size()==0){
				//当没找到对应logo,说明之前没上传过
				LogoDto saveEntity = new LogoDto();
				saveEntity.setDelFlag(DelFlagEnum.UNDEL.getNo());
				saveEntity.setLogoMerchantid(entity.getId());
				saveEntity.setLogoType(LogoTypeEnum.TYPE_3.getNo());
				saveEntity.setLogoUrl(entity.getAssiantIndexLogo());
				logoService.create(saveEntity);
			}
		}
		if(StringUtils.isNotBlank(entity.getAssiantExitLogo())){
			LogoDto logo4 = new LogoDto();
			logo4.setLogoMerchantid(entity.getId());
			logo4.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo4.setLogoType(LogoTypeEnum.TYPE_4.getNo());
			List<Logo> list = logoService.selectListByDto(logo4);
			if(list.size()==1){
				logo4.setLogoUrl(entity.getAssiantExitLogo());
				logo4.setId(list.get(0).getId());
				logoService.update(logo4);
			}else if(list.size()==0){
				//当没找到对应logo,说明之前没上传过
				LogoDto saveEntity = new LogoDto();
				saveEntity.setDelFlag(DelFlagEnum.UNDEL.getNo());
				saveEntity.setLogoMerchantid(entity.getId());
				saveEntity.setLogoType(LogoTypeEnum.TYPE_4.getNo());
				saveEntity.setLogoUrl(entity.getAssiantExitLogo());
				logoService.create(saveEntity);
			}
		}
		if(StringUtils.isNotBlank(entity.getDevelopersLoginLogo())){
			LogoDto logo5 = new LogoDto();
			logo5.setLogoMerchantid(entity.getId());
			logo5.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo5.setLogoType(LogoTypeEnum.TYPE_5.getNo());
			List<Logo> list = logoService.selectListByDto(logo5);
			if(list.size()==1){
				logo5.setLogoUrl(entity.getDevelopersLoginLogo());
				logo5.setId(list.get(0).getId());
				logoService.update(logo5);
			}else if(list.size()==0){
				//当没找到对应logo,说明之前没上传过
				LogoDto saveEntity = new LogoDto();
				saveEntity.setDelFlag(DelFlagEnum.UNDEL.getNo());
				saveEntity.setLogoMerchantid(entity.getId());
				saveEntity.setLogoType(LogoTypeEnum.TYPE_5.getNo());
				saveEntity.setLogoUrl(entity.getDevelopersLoginLogo());
				logoService.create(saveEntity);
			}
		}
		if(StringUtils.isNotBlank(entity.getDevelopersIndexLogo())){
			LogoDto logo6 = new LogoDto();
			logo6.setLogoMerchantid(entity.getId());
			logo6.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo6.setLogoType(LogoTypeEnum.TYPE_6.getNo());
			List<Logo> list = logoService.selectListByDto(logo6);
			if(list.size()==1){
				logo6.setLogoUrl(entity.getDevelopersIndexLogo());
				logo6.setId(list.get(0).getId());
				logoService.update(logo6);
			}else if(list.size()==0){
				//当没找到对应logo,说明之前没上传过
				LogoDto saveEntity = new LogoDto();
				saveEntity.setDelFlag(DelFlagEnum.UNDEL.getNo());
				saveEntity.setLogoMerchantid(entity.getId());
				saveEntity.setLogoType(LogoTypeEnum.TYPE_6.getNo());
				saveEntity.setLogoUrl(entity.getDevelopersIndexLogo());
				logoService.create(saveEntity);
			}
		}
		if(StringUtils.isNotBlank(entity.getAgencyLoginLogo())){
			LogoDto logo7 = new LogoDto();
			logo7.setLogoMerchantid(entity.getId());
			logo7.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo7.setLogoType(LogoTypeEnum.TYPE_7.getNo());
			List<Logo> list = logoService.selectListByDto(logo7);
			if(list.size()==1){
				logo7.setLogoUrl(entity.getAgencyLoginLogo());
				logo7.setId(list.get(0).getId());
				logoService.update(logo7);
			}else if(list.size()==0){
				//当没找到对应logo,说明之前没上传过
				LogoDto saveEntity = new LogoDto();
				saveEntity.setDelFlag(DelFlagEnum.UNDEL.getNo());
				saveEntity.setLogoMerchantid(entity.getId());
				saveEntity.setLogoType(LogoTypeEnum.TYPE_7.getNo());
				saveEntity.setLogoUrl(entity.getAgencyLoginLogo());
				logoService.create(saveEntity);
			}
		}
		if(StringUtils.isNotBlank(entity.getAgencyIndexLogo())){
			LogoDto logo8 = new LogoDto();
			logo8.setLogoMerchantid(entity.getId());
			logo8.setDelFlag(DelFlagEnum.UNDEL.getNo());
			logo8.setLogoType(LogoTypeEnum.TYPE_8.getNo());
			List<Logo> list = logoService.selectListByDto(logo8);
			if(list.size()==1){
				logo8.setLogoUrl(entity.getAgencyIndexLogo());
				logo8.setId(list.get(0).getId());
				logoService.update(logo8);
			}else if(list.size()==0){
				//当没找到对应logo,说明之前没上传过
				LogoDto saveEntity = new LogoDto();
				saveEntity.setDelFlag(DelFlagEnum.UNDEL.getNo());
				saveEntity.setLogoMerchantid(entity.getId());
				saveEntity.setLogoType(LogoTypeEnum.TYPE_8.getNo());
				saveEntity.setLogoUrl(entity.getAgencyIndexLogo());
				logoService.create(saveEntity);
			}
		}
	}
	@Override
	public boolean getCommissionFlag(Long higherId){
		Company company = selectById(higherId);
		boolean flag = true;
		if("0".equals(company.getCommissionFlag())){
			flag = false;
		}
		return flag;

	}
	public void updateCompany(CompanyDto entity){
		if(20==entity.getCompanyType()){
			CompanyRelationDto relation = new CompanyRelationDto();
			relation.setDelFlag(DelFlagEnum.UNDEL.getNo());
			relation.setDevCompany(entity.getId());
			List<CompanyRelation> lists = companyRelationService.selectListByDto(relation);
			for(CompanyRelation re:lists){
				Company company = new Company();
				Company com = mapper.selectById(re.getAgentCompany());
				company.setCity(com.getCity());
				company.setDomain(com.getDomain());
				company.setMerchantCode(com.getMerchantCode());
				company.setId(re.getAgentCompany());
				company.setCommissionFlag(entity.getCommissionFlag());
				mapper.edit(company);
			}
		}
	}

	@Override
	public boolean getMessageFlag(Long higherId) {
		boolean flag =true;
		Company company = selectById(higherId);
		if("0".equals(company.getMessageFlag())){
			flag = false;
		}
		return flag;
	}
	@Override
	public List<CompanyDto> selectListByIds(CompanyDto cDto) {
		// TODO Auto-generated method stub
		return mapper.selectListByIds(cDto);
	}

	@Override
	public List<Company> selectMyListByDto(CompanyDto entity) {
		// TODO Auto-generated method stub
		return mapper.selectMyListByDto(entity);
	}

	@Override
	public String getCompanyCode(Company company) {
		String code = "";//公司机构代码
    	String regEx = "[a-zA-Z]";
    	String companyName = company.getCompanyName();
    	String firstLetter = ChineseCharToEn.getFirstLetter(companyName);
		boolean flag = Pattern.matches(regEx,firstLetter);
		CompanyDto entity = new CompanyDto();
		//entity.setCompanyName(companyName.substring(0,1));
		if(flag){
			firstLetter = firstLetter.toUpperCase();
			entity.setSql(" company_code like concat('"+firstLetter+"','%') ");
			entity.setOrders("company_code desc,create_time desc");
		}else{
			firstLetter = "V";
			entity.setSql("company_code like concat('"+firstLetter+"','%')");
			entity.setOrders("company_code desc,create_time desc");
		}
		List<Company> list = mapper.selectMyListByDto(entity);
		if(list.size()>0){
			//获取创建时间最大的一个合作机构信息
			Company com = list.get(0);
			String companyCode = com.getCompanyCode();
			if(!StringUtils.isEmpty(companyCode)){
				String subStr = companyCode.substring(1, companyCode.length());
				code = firstLetter+addNum(Integer.parseInt(subStr));
			}else{
				code = firstLetter+"00001";
			}
		}else{
			code = firstLetter+"00001";
		}
		return code;
	}
	 private static String addNum(int i){
			String str = "";
			int sum = i+1;
			if((sum+"").length()==1){
				str = "0000"+sum;
			}else if((sum+"").length()==2){
				str = "000"+sum;
			}else if((sum+"").length()==3){
				str = "00"+sum;
			}else if((sum+"").length()==4){
				str = "0"+sum;
			}
			return str;
		}

	@Override
	@Transactional(rollbackFor=Exception.class,isolation = Isolation.SERIALIZABLE,propagation = Propagation.REQUIRED)
	public int updateStatus(CompanyDto entity, PartnerInfo pi){
		int result = 0;
        String status = entity.getStatus();
        if (CheckStatusEnum.SUCCESS.getNo().equals(status)) {
            PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
			partnerInfoDto.setPhone(entity.getPhone());
        	List<Long> companyIds = partnerInfoService.listGroupCompanyId(null,entity.getCompanyUuid());
        	partnerInfoDto.setCompanyIds(companyIds);
			List<PartnerInfo> partnerInfos = partnerInfoService.checkRepeat(partnerInfoDto);

            if (partnerInfos != null && partnerInfos.size() >  0) {
            	for(PartnerInfo pInfo: partnerInfos){
					if("-1".equals(String.valueOf(pInfo.getUserRoleId()))){
						continue;
					}else{
						throw new TServerException("9999","审核失败，手机号已存在账户");
					}
				}
            }
        }

		Company company = mapper.selectById(entity.getId());
		if (company != null) {
            CompanyDto cdto = new CompanyDto();
			String companyCode = this.getCompanyCode(company);
			if(CheckStatusEnum.SUCCESS.getNo().equals(status)) {
                cdto.setDelFlag(DelFlagEnum.UNDEL.getNo());
                cdto.setCompanyCode(companyCode);
			}
            cdto.setUpdateTime(new Date());
            cdto.setCity(company.getCity());
            cdto.setCreateUserId(company.getCreateUserId());
            cdto.setChargeMan(company.getChargeMan());
            cdto.setPhone(company.getPhone());
			cdto.setStatus(entity.getStatus());
			cdto.setId(entity.getId());
			//更新company 信息
			result = mapper.edit(cdto);
			if (result <= 0) {
				throw new TServerException("更新公司信息失败");
			}

			if (CheckStatusEnum.SUCCESS.getNo().equals(status)) {
                //更新department 信息
                DepartmentDto departmentDto = new DepartmentDto();
                departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
                departmentDto.setMerchantId(entity.getId());
                result = departmentMapper.updateByMerchantId2(departmentDto);
                if (result <= 0) {
                    throw new TServerException("更新机构信息失败");
                }
				//审核成功情况下，将申请人和负责人信息录入系统
				result = addUserInfo(entity,pi);
				if (result <= 0) {
					throw new TServerException("更新申请人和负责人信息异常");
				}
				//将开发商的楼盘分配给分销商
				result = updateAgentPremises(entity,pi);
				if (result <= 0) {
					throw new TServerException("将开发商的楼盘分配给分销商异常");
				}
			}
		}else {
			throw new TServerException("未查询到公司信息");
		}
		return result;
	}

	public int updateCompanyRelation(CompanyDto entity, PartnerInfo pi) {
		CompanyRelation cr = new CompanyRelation();
		cr.setAgentCompany(entity.getId());
		cr.setDevCompany(pi.getHigherid());
		cr.setDelFlag(DelFlagEnum.UNDEL.getNo());
		cr.setRelationStatus(RelationStatusEnum.VALID.getNo());
		cr.setUpdateTime(new Date());
		cr.setUpdateUserId(pi.getId());
		return companyRelationMapper.editByDevAndAgentId(cr);
	}

	public int updateAgentPremises(CompanyDto entity, PartnerInfo pi) {
		int result = 0;
		//查询该开发商下的所有楼盘
		PremisesDto pDto = new PremisesDto();
		pDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		pDto.setCompanyId(pi.getHigherid());
		List<Premises> lists = premisesService.selectListByDto(pDto);
		for(Premises premises:lists){
			//在楼盘合作关系表中绑定合作机构和楼盘信息
			PremisesRelationDto relationDto = new PremisesRelationDto();
			relationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			relationDto.setDevCompanyId(pi.getHigherid());
			relationDto.setAgentCompanyId(entity.getId());
			relationDto.setPremisesId(premises.getId());
			relationDto.setStatus(MechanismStatusEnum.enable.getNo());
			relationDto = premisesRelationService.create(relationDto);
			if (relationDto.getId() <= 0) {
				return result=0;
			}else {
				result = 1;
			}
		}
		return result;
	}

	public int addUserInfo(CompanyDto entity, PartnerInfo pi) throws TServerException  {
		int result = 0;
		String phone = entity.getPhone();
		String applyUserPhone = entity.getApplyUserPhone();
		//如果申请人和负责人电话号码一样，将申请人设为管理员
		if (applyUserPhone.equals(phone)) {
			result = updateApplyUserInfo(entity);
		} else {
			//如果申请人和负责人电话号码不一样，将负责人添加到tm_partner_info(需要校验唯一性)中并设为管理员
			// ，将申请人注册在该公司下（无角色）
			//关于上面注释的补充说明：后面的代码逻辑并没有校验 在前面代码里面有判断过同一域名下不存在这个手机号
			result = updateApplyUserAndChargeManInfo(entity,pi);
		}
		return result;
	}

	public int updateApplyUserAndChargeManInfo(CompanyDto entity, PartnerInfo pi) throws TServerException {
		int result = 0;

		DepartmentDto departmentDto = new DepartmentDto();
		departmentDto.setMerchantId(entity.getId());
		Department departmentInfo = departmentDao.selectByDto(departmentDto);
		//将负责人信息添加进系统并将负责人设为管理员
		result = addUserInfo(entity,departmentInfo);
		if (result <= 0) {
			throw new TServerException("添加负责人信息异常");
		}
		//将申请人注册在该申请公司下
		result = updateUserInfo(entity,departmentInfo);
		if (result <= 0) {
			throw new TServerException("更新申请人信息异常");
		}
		return result;
	}

	public int updateUserInfo(CompanyDto entity,Department departmentInfo) throws TServerException  {
		int result = 0;
		PartnerInfoDto pid = new PartnerInfoDto();
		pid.setId(entity.getCreateUserId());
		pid.setHigherid(entity.getId());
		pid.setDeptId(departmentInfo.getId());
		pid.setUserRoleId(Long.valueOf(PartnerInfoEnum.NO_ROLER.getCode()));
		result =  partnerInfoService.update(pid);
		if(result <= 0) {
			throw new TServerException("更新申请人信息异常");
		}
		return result;
	}

	public int addUserInfo(CompanyDto entity, Department departmentInfo) throws TServerException  {
		int result = 0;
		PartnerInfoDto pInfoDto = new PartnerInfoDto();
		pInfoDto.setPhone(entity.getPhone());
		pInfoDto.setAccountName(entity.getChargeMan());
//		pInfoDto.setPassword(PasswordUtil.md5Hex("x1234567"));
		String pwd = PasswordUtil.generateRandomPwd(8);
		pInfoDto.setPassword(PasswordUtil.md5Hex(pwd));
		pInfoDto.setAccountType(PartnerInfoEnum.ACCOUNT_MECHANISM.getCode());
		pInfoDto.setCreateTime(new Date());
		pInfoDto.setUpdateTime(new Date());
		pInfoDto.setStatus(PartnerInfoEnum.STATUS_ENABLE.getCode());
		pInfoDto.setHigherid(entity.getId());
		pInfoDto.setDeptId(departmentInfo.getId());
		pInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		pInfoDto.setUserRoleId(Long.valueOf(PartnerInfoEnum.NO_ROLER.getCode()));
		pInfoDto.setIsAdmin("0");
		pInfoDto = partnerInfoService.create(pInfoDto);
		if (pInfoDto == null || pInfoDto.getId() <= 0) {
			throw new TServerException("新增负责人信息异常");
		}else {
			result = 1;
		}
		//新用户短信通知
		if(result == 1){
			//获取公司
			CompanyRelationDto companyRelation = new CompanyRelationDto();
			companyRelation.setAgentCompany(entity.getId());
			companyRelation.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<CompanyRelation> companyRelationList = companyRelationMapper.selectListByDto(companyRelation);
			if(companyRelationList !=null && companyRelationList.size() > 0){
				sendRegistSms(entity.getPhone(),pwd,companyRelationList.get(0).getDevCompany());
			}
		}
		return result;
	}

	public int updateApplyUserInfo(CompanyDto entity) throws TServerException  {
		int result = 0;
		PartnerInfo pi = partnerInfoService.selectById(entity.getCreateUserId());
		if (pi != null) {
			DepartmentDto departmentDto = new DepartmentDto();
			departmentDto.setMerchantId(entity.getId());
			Department departmentInfo = departmentDao.selectByDto(departmentDto);
			PartnerInfoDto pid = new PartnerInfoDto();
			pid.setId(pi.getId());
			pid.setIsAdmin("0");
			pid.setUserRoleId(Long.valueOf(PartnerInfoEnum.NO_ROLER.getCode()));
			pid.setAccountType(PartnerInfoEnum.ACCOUNT_MECHANISM.getCode());//设为管理员
			pid.setDeptId(departmentInfo.getId());
			pid.setHigherid(entity.getId());
			result =  partnerInfoService.update(pid);
			if(result <= 0) {
				throw new TServerException("更新用户信息表出错");
			}
		} else {
			throw new TServerException("未查询到用户信息");
		}
		return result;
	}

	@Override
	@Transactional(readOnly=true)
	public Page<CompanyDto> selectDtoListById(CompanyDto entity, int begin, int end) {
		entity.setOrders("status asc,create_time desc");
		int total = mapper.selectDtoCountById(entity,begin,end);
		List<CompanyDto> rows = mapper.selectDtoListById(entity,begin,end);
		Page<CompanyDto> pageModel = new Page<CompanyDto>(total,rows);
		return pageModel;
	}

	/**
	 * 查询该楼盘下未设置过佣金规则的合作机构
	 * @param devCompanyId
	 * @param premeiseId
	 * @return
	 */
	@Override
	public List<CompanyRelationDto> findCompanysForCommissionRule(Long devCompanyId,Long premeiseId){
		//1.查询所有开发商的合作机构
		CompanyRelationDto companyRelationDto = new CompanyRelationDto();
		companyRelationDto.setDevCompany(devCompanyId);
		companyRelationDto.setPremisesId(premeiseId+"");
		List<CompanyRelationDto> listAgency = companyRelationMapper.selectPremisesListByDto(companyRelationDto);
		//2.查询已设置规则的合作机构
		CommissionRuleParentDto commissionRuleParentDto = new CommissionRuleParentDto();
		commissionRuleParentDto.setPremisesId(premeiseId);
		List<CommissionRuleParent> commissionRuleParentList = commissionRuleParentMapper.selectListForAddCommission(commissionRuleParentDto);
		Map<Long,CommissionRuleParent> map = new HashMap<Long, CommissionRuleParent>();
		for(CommissionRuleParent crp : commissionRuleParentList){
			map.put(crp.getCompanyId(),crp);
		}
		//3.过滤已设置规则的合作机构
		if(listAgency != null) {
			Iterator<CompanyRelationDto> iterator = listAgency.iterator();
			while (iterator.hasNext()){
				CompanyRelationDto d = iterator.next();
				if (map.containsKey(d.getAgentCompany())) {
					iterator.remove();
				}
			}
		}
		return listAgency;
	}
	
	/**
	 * 根据域名,获取开发商
	 * @param 域名
	 * @return 
	 */
	@Override
	public Long getCompanyIdByDomain(String domain){
		Long companyId = null;
		if(StringUtils.isEmpty(domain)){
			return companyId;
		}
		try {
			CompanyDto cDto = new CompanyDto();
			cDto.setDomain(domain);
			cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());//0待审核1审核失败2审核成功
			cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<Company> list = mapper.selectListByDto(cDto);
			if (list == null || list.size() == 0) {
				return null;
			}
			companyId = list.get(0).getId();
		} catch (Exception e) {
			logger.error("getCompanyIdByDomain error: {}", e);
			return null;
		}
		return companyId;
	}

	/**
	 * 根据域名,获取开发商
	 * @param companyCode
	 * @return
	 */
	@Override
	public String getDevCompanyByAgentCompanyCode(String companyCode){
		String companyUuid = null;
		try {
			CompanyDto cDto = new CompanyDto();
			cDto.setCompanyCode(companyCode);
			cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());//0待审核1审核失败2审核成功
			cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<Company> list = mapper.getDevCompanyByAgentCompanyCode(cDto);
			if (list == null || list.size() == 0) {
				return null;
			}
			companyUuid = list.get(0).getCompanyUuid();
		} catch (Exception e) {
			logger.error("getDevCompanyByAgentCompanyCode companyCode: {}, error: ", companyCode, e);
			return null;
		}
		return companyUuid;
	}

	private void sendRegistSms(String phone,String pwd,Long companyId){

		String messageContent = "【分销助手】您已注册成功，您的初始密码为:" + pwd + "，请及时修改！";

		//获取短信设置,功能已变更.设置已用于定制化号码验真.此处不能保留
		Map<String, String> smsSettingMap = null;
//		Map<String, String> smsSettingMap = smsSettingService.getSmsSettingMap(null, companyId,null);
		Map<String,String> qfSmsMap = new HashMap<>();
		qfSmsMap.put("key1",pwd);
		Map<String, Object> returnMap = smsUtil.sendMessage(messageContent,phone, QfSmsTemplateEnum.SMS_REGISTER_SUCCESS.getId(), smsSettingMap,qfSmsMap);
		boolean sendStatus = (Boolean) returnMap.get("sendStatus");
		String sendRes = String.valueOf(returnMap.get("sendRes"));
		//添加进历史表
		SmsHistoryDto history = new SmsHistoryDto();
		history.setContent(messageContent);
		history.setReceiver(phone);
		if(companyId != null){
			history.setMerchantId(companyId);
		}else{
			history.setMerchantId(0L);
		}
		history.setSender("qiaofang");
		if(null != smsSettingMap) {
			history.setSender(smsSettingMap.get("userName"));
		}
		history.setRemark(SMSTypeEnum.TYPE_13.getDes());
		history.setCreateTime(new Date());
		history.setCreateUserId(0l);
		if(sendStatus){
			logger.info(messageContent);
			history.setSendStatus(SendStatusEnum.SUCCESS.getNo());
		}else{
			history.setSendStatus(SendStatusEnum.FAILURE.getNo());
		}
		history.setSendRes(sendRes);
		if(returnMap.containsKey("orderUuid")){
			history.setOrderUuid(String.valueOf(returnMap.get("orderUuid")));
		}
		if(returnMap.containsKey("platform")){
			history.setPlatform(String.valueOf(returnMap.get("platform")));
		}
		smsHistoryService.create(history);
	}

	@Override
	public Organization getOrganizationInfo(Long higherId, Long deptId) {
		Organization organization = new Organization();
		//经纪人公司名称
		Company company = selectById(higherId);
		organization.setCompanyName(company != null ? company.getCompanyName() : "");
		// 经纪人部门名称
		Department dept = departmentDao.selectById(deptId);
		if(Objects.nonNull(dept)){
			organization.setDepartmentName(dept.getDepartmentName());
		}
		organization.setStoreName(dept != null && dept.getParentId() != 0 ? dept.getDepartmentName() : "");
		// 经纪人组别名称
		if (dept == null) {
			organization.setGroupName("");
		} else {
			Department groupDept = departmentDao.selectById(dept.getParentId());
			organization.setGroupName(groupDept != null && groupDept.getParentId() != 0 ? groupDept.getDepartmentName() : "");
		}
		return organization;
	}
	
	/**
	 * 
	 * @param agentPhone  分销人手机号码
	 * @param companyUuid	总代公司Uuid
	 * @return
	 */
	@Override
	public Map<String, Object> getAgentInfo(String agentPhone, String companyUuid){
		return mapper.getAgentInfo(agentPhone, companyUuid);
	}

}
